/**
 * Excel套用模板批量转Word 
 * 时间：2022年11月14日10:49:12
 * 版权声明：未经许可不得作为商业用途，仅供学习使用，转载必须注明来源及作者。
 **/
 let PizZip = require('pizzip');
 let Docxtemplater = require('docxtemplater');
 let fs = require('fs');
 let path = require('path');
 let xlsx = require('node-xlsx');

 //目录工具函数
 mkdir = async function (folderpath) {
     console.log("打印创建目录：");
     console.log(folderpath);
     try {
         const pathArr = folderpath.split('/');
         console.log(pathArr);
         let _path = '';
         for (let i = 0; i < pathArr.length; i++) {
             if (pathArr[i]) {
                 _path += `${pathArr[i]}/`;
                 console.log(_path);
                 console.log(fs.existsSync(_path));
                 if (!fs.existsSync(_path)) {
                     fs.mkdirSync(_path);
                 }
             }
         }
     } catch (e) { }
 }
 
 //读取映射表格数据
 let settingObj = xlsx.parse(path.resolve(__dirname,'setting.xlsx'));
 let setting = settingObj[0].data;
 let startNum = setting[0][1] - 1;
 let docname = setting[1][1];
 let xlsname = setting[2][1];
 
 let outputFile = setting[3][1] - 1;
 let outputDir = setting[4][1];
 // console.log(setting)
 
 //读取表格数据
 let dataObj = xlsx.parse(path.resolve(__dirname,xlsname));
 //sheet1
 let s1 = dataObj[0].data;
 // console.log(s1)
 
 mkdir(path.resolve(__dirname,'./'+outputDir));
 
 //循环输出
 let keyObj = {};
 for(var i=startNum;i<s1.length;i++){
 	for(var j=5;j<setting.length;j++){
 		keyObj[setting[j][0]] = s1[i][setting[j][1] - 1];
 	}
 	let content = fs.readFileSync(path.resolve(__dirname,docname),'binary');
 	let zip = new PizZip(content);
 	//模板文件中变量使用：{username}，{phone}
 	let doc = new Docxtemplater(zip);
 	doc.setData(keyObj);
 	console.log(keyObj);
 	doc.render();
 	let buf = doc.getZip().generate({type:'nodebuffer'});
 	fs.writeFileSync(path.resolve(__dirname,'./'+outputDir+'/'+s1[i][outputFile]+'.docx'),buf);
 }
